﻿using DataAchive.xamls;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Windows.Xps;
using System.Windows.Xps.Packaging;

namespace DataAchive
{
    /// <summary>
    /// Preview.xaml 的交互逻辑
    /// </summary>
    public partial class Preview : Window
    {
        private readonly FlowDocument m_doc;
        private readonly object m_data;
        private delegate void LoadXpsMethod();
        public Preview()
        {
            InitializeComponent();
        }

        public Preview(string strTemplate, object data, IDocRender docRender = null)
        {
            InitializeComponent();
            m_data = data;
            m_doc = LoadDocumentAndRender(strTemplate, data, docRender);
            Dispatcher.Invoke( new LoadXpsMethod(LoadXps), DispatcherPriority.ApplicationIdle);
        }

        static FlowDocument LoadDocumentAndRender(string strTemplate, object data, IDocRender render = null)
        {
            FlowDocument doc = (FlowDocument)Application.LoadComponent(new Uri(strTemplate, UriKind.RelativeOrAbsolute));
            doc.PagePadding = new Thickness(10);
            doc.DataContext = data;
            if (render != null)
            {
                render.Render(doc, data);
            }
            return doc;

        }


        void LoadXps()
        {
            MemoryStream ms = new MemoryStream();
            Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
            // Uri documentUri = new Uri("pack://InMemoryDocument.xps");

            Uri documentUri = PackUriHelper.Create(new Uri("inmemory:document.xps"));
         
            if (!UriParser.IsKnownScheme("inmemory"))
            {
                UriParser.Register(new GenericUriParser(GenericUriParserOptions.GenericAuthority), "inmemory", -1);
            }

            PackageStore.RemovePackage(documentUri);
            PackageStore.AddPackage(documentUri,package);
            XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Fast, documentUri.AbsoluteUri);
            XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
            writer.Write(((IDocumentPaginatorSource)m_doc).DocumentPaginator);
            docViewer.Document = xpsDocument.GetFixedDocumentSequence();
            xpsDocument.Close();



        }
    }
}
